import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import qs from 'qs';
import { storage } from '@/util';
/**
 * 时间: 2019年12月20日09:44:50
 * 作者: niezhangxun
 * 功能: 线上vue版本热更新
 * 缺陷: 无法自动添加版本号,需人为手动添加版本号后再打包
 */
var VUEVER = 201912241358;
//域名
var baseUrl;
if (window.location.port == 6161) {
  baseUrl = 'http://www.l.xyou.cn:6161/';
} else {
  baseUrl = 'https://app.youyizhuan.cn/';
}
//api接口
let proxyKey;
if (process.env.NODE_ENV === 'development') {
  proxyKey = 'http://api.l.xyou.cn/youyizhuan/web';
} else if (window.location.port == 6161) {
  proxyKey = 'http://api.l.xyou.cn/youyizhuan/web';
} else {
  proxyKey = 'https://api.youyizhuan.cn/web';
}
// 初始化更新记录缓存
storage.set('ClearUpdateTimes', false) 
function dialog(txt, error) {
  console.log(error)
  window.$JsBridge.callHandler('natShowDialog',{type: 5, back_enable: 0, style_content: {is_html: false, text: txt, gravity: 0}, btn_one:{text: '刷新'}, errorMsg: error}, res => {
    let resData = JSON.parse(res);
    if (resData.click_btn_index == 0) {
      window.$JsBridge.callHandler('natWebReload',{},() => {})
    }
  })
}

axios.defaults.timeout = 5000;

axios.defaults.headers = {
  "Content-Type": "application/x-www-form-urlencoded"
};

axios.interceptors.request.use(
  config => {
    // config.data = qs.stringify(config.data);
    // console.log(config)
    // console.log(config.data)
    if (config.method === 'get') {
      if (config.url.includes('/download')) {
        config.params = {
          ...config.params,
        };
      } else {
        if (config.data && config.data.notPro) {   // 非app项目内请求, 在data中添加字段判断
          config.params = {
            ...config.data,
          };
        } else {
          config.params = {
            ...config.params,
            token: storage.get('token'),
            vue_ver: VUEVER,
          };
        }
      }
    }
    !config.headers['Content-Type']
      ? (config.headers['Content-Type'] = 'application/x-www-form-urlencoded')
      : void 666;
    
    if (
      config.method.toLowerCase() === 'post' &&
      config.data &&
      config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      config.data = {
        ...config.data,
        token: storage.get('token'),
        vue_ver: VUEVER,
      };
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(response => {
  let res = response.data;
  // console.log(response)
  //全局弹窗通知
  let globalPopuData = response.data.popup;
  if (globalPopuData) {
    if(globalPopuData.length > 0) {
      if (res.popup[0].update_type == 1) {
        // 触发了强制更新的状态, 清除当前更新计算值重新计算
        storage.set('ClearUpdateTimes', true);
      }
      if (globalPopuData[0]['version']) {
        // 更新
        if (storage.get('APP_Ver') != globalPopuData[0]['version'] || res.popup[0].update_type == 1) {
          popupFun(globalPopuData,0);
        }
      } else {
        popupFun(globalPopuData,0);
      }
    }
  }
  // 拦截全局更新字段
  if (res.ext) {
    if (res.ext.del_update_mark) {
      if (storage.get('token')) {
        window.$get('/update')
        .then(res => {
          console.log(res)
        })
      }
    }
  }
  return res;
}, error => {
  // console.log(error)
  let res = error.response
  // 请求错误处理
  // console.log(res)
  // console.log(res.status)
  // console.log(error.config)
  if (res) {
    if (res.status == 303) {
      // 该状态下判断到rds最新记录的版本号与客户端版本号不符合,强制触发更新
      var url = window.location.href;
      var time = new Date().getTime();
      if (url.indexOf("?",0) > -1) {
        location.replace(url + '&t=' + time);
      } else {
        location.replace(url + '?t=' + time);
      }
      // window.$JsBridge.callHandler('natWebReload',{},() => {})
      return;
    } else if (res.status == 400) {
      dialog(res.data && res.data.errorMsg || '错误的请求');
      return;
    } else if (res.status == 401) { // 用户未登录
      if (window.location.href.search('login') > -1) {
        // storage.remove('token');
        return;
      } else {
        storage.remove('token');
        window.$JsBridge.callHandler('natDelToken', {}, () => {});
        window.location.href = '/login';
      }
      return;
    } else if (res.status == 403) {
      // no magic here
      window.location.href = baseUrl + 'login?lock_toast=1';
      return;
    } else if (res.status == 500) {
      dialog('服务器内部错误');
      return;
    } else if (res.status == 502) {
      dialog('连接超时，请检查网络');
      return;
    } else {
      dialog('未知错误');
      return;
    }
  }
  if (error.config.url.search('/exitPop') > -1) {
    return Promise.reject(error);
  } else if (error.message.search('Network Error') > -1) {
    // 仅在网络出现故障的情况下才会弹该窗口,如果经常出现要注意是否有太多请求阻塞了
    dialog('网络走丢了,请检查网络后刷新', {error: error});
  }
  return Promise.reject(error);
});
//全局弹窗
function popupFun(globalPopuData,clickIndex){
  window.$globalCurrentPopuData = globalPopuData[clickIndex];
  globalPopuData[clickIndex]['popupShow'] = true;
  globalPopuData[clickIndex]['clickClose'] = function(){
     globalPopuData[clickIndex]['popupShow'] = false;
     clickIndex++;
     if(clickIndex < globalPopuData.length){
       popupFun(globalPopuData,clickIndex);
     }
  };
  globalPopuData[clickIndex]['popupClickLeft'] = function(){
    globalPopuData[clickIndex]['popupShow'] = false;
    if (globalPopuData[clickIndex]['type'] == 14 && globalPopuData[clickIndex]['update_type'] == 1) {
     window.$JsBridge.callHandler('natAppUpdate',{apk_url: globalPopuData[clickIndex]['url'], type: 1}, res => {
       storage.set('ClearUpdateTimes', false)
       let resData = JSON.parse(res);
       if (resData.result == 1) {
         console.log(resData.result)
       }
     })
    } else if (globalPopuData[clickIndex]['type'] == 14 && globalPopuData[clickIndex]['update_type'] == 2) {
      storage.set('APP_Ver', globalPopuData[clickIndex]['version'])
    }
    clickIndex++;
    if(clickIndex < globalPopuData.length){
     popupFun(globalPopuData,clickIndex);
    }
  };
  globalPopuData[clickIndex]['popupClickRight'] = function(){
     globalPopuData[clickIndex]['popupShow'] = false;
     if(globalPopuData[clickIndex]['type'] == 14) {
       window.$JsBridge.callHandler('natAppUpdate',{apk_url: globalPopuData[clickIndex]['url'], type: 0}, res => {
         storage.set('ClearUpdateTimes', false)
         let resData = JSON.parse(res);
         if (resData.result == 1) {
           console.log(resData.result)
         }
       })
     }
     clickIndex++;
     if(clickIndex < globalPopuData.length){
       popupFun(globalPopuData,clickIndex);
     }
  };
  let pdata = {
    globalPopuData : globalPopuData[clickIndex]
  };
  if(globalPopuData) {
    window.$globalPopu.install(pdata);
  }
}

Vue.use(VueAxios, axios);
// proxyKey = 'https://api.youyizhuan.cn/web';
Vue.prototype.$get = (api, params) => {
  let url = proxyKey + api;
  return Vue.axios.get(url, {
    params: params || {}
  });
};

Vue.prototype.$post = (api, params) => {
  return Vue.axios.post(proxyKey + api, params);
};

window.$get = Vue.prototype.$get;